package ru.housewife.service.userstables;

import org.hibernate.Query;
import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.form.UsersTableForm;

/**
 * removing users table
 *
 * @author Alexander Troshanin
 */
public class RemoveUsersTable implements HibernateAction<Boolean> {

    private UsersTableForm usersTableForm; // to be removed

    public RemoveUsersTable(UsersTableForm usersTableForm) {
        this.usersTableForm = usersTableForm;
    }
    @Override
    public Boolean execute(Session session) {
        Query q = session.createQuery("delete from UsersTable where id=:tableId and user.id=:userId");
        q.setLong("tableId", usersTableForm.getId());
        q.setLong("userId", usersTableForm.getUser().getId());
        if (q.executeUpdate() == 0) {
            return false;
        }

        usersTableForm.getUser().removeUsersTable(usersTableForm.getId());
        return true;


/*
        User user = (User) session.get(User.class, userForm.getId());
        if (user == null) {
            return false;
        }

        for (Iterator<UsersTable> iter = user.getUsersTables().iterator(); iter.hasNext();) {
            UsersTable usersTable = iter.next();
            if (usersTable.getId() == usersTableId) {
                iter.remove();
                session.save(user);

                for (Iterator<UsersTableForm> iterF = userForm.getUsersTables().iterator(); iterF.hasNext();) {
                    UsersTableForm usersTableForm = iterF.next();
                    if (usersTableForm.getId() == usersTableId) {
                        iterF.remove();
                        break;
                    }
                }

                return true;
            }
        }

        return false;
*/
    }
}
